import { login, logout, getInfo, getMyInfo } from '@/api/login'
import { getToken, setToken, removeToken } from '@/utils/auth'
import { isEmpty } from "@/utils/validate"
import defAva from '@/assets/images/profile.jpg'

const useUserStore = defineStore(
  'user',
  {
    state: () => ({
      token: getToken(),
      id: '',
      name: '',
      phone: '',
      nickname: '',
      avatar: {},
      remark: '',
      roles: [],
      permissions: []
    }),
    actions: {
      // 登录
      login(userInfo) {
        return new Promise((resolve, reject) => {
          login(userInfo).then(res => {
            setToken(res.result)
            this.token = res.result
            resolve()
          }).catch(error => {
            reject(error)
          })
        })
      },
      // 获取用户信息
      getInfo() {
        return new Promise((resolve, reject) => {
          getInfo().then(res => {
            const result = res.result || {}
            if (result.roles && result.roles.length > 0) { // 验证返回的roles是否是一个非空数组
              this.roles = result.roles
              this.permissions = result.perms
            } else {
              this.roles = ['ROLE_DEFAULT']
            }
            getMyInfo().then(response => {
              let user = response.result || {}
              let avatar = user.avatar || {furl: defAva}
              this.id = user.userId
              this.name = user.username
              this.phone = user.phone
              this.nickname = user.nickname
              this.avatar = avatar
              this.remark = user.remark
              resolve(res)
            }).catch(error => {
              reject(error)
            })
          }).catch(error => {
            reject(error)
          })
        })
      },
      // 退出系统
      logOut() {
        return new Promise((resolve, reject) => {
          logout(this.token).then(() => {
            this.token = ''
            this.roles = []
            this.permissions = []
            removeToken()
            resolve()
          }).catch(error => {
            reject(error)
          })
        })
      }
    }
  })

export default useUserStore
